package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mapper.UserMapper;
import cn.wolfcode.shop.cloud.redis.RedisService;
import cn.wolfcode.shop.cloud.service.IUserService;
import cn.wolfcode.shop.cloud.util.Md5Util;
import cn.wolfcode.shop.cloud.util.MemberCodeMsg;
import cn.wolfcode.shop.cloud.util.MemberRedsKeyPrefix;
import cn.wolfcode.shop.cloud.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public User findById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public String doLogin(LoginVO loginVO) {
        //验证参数是否为空
        if (StringUtils.isEmpty(loginVO.getUsername()) || StringUtils.isEmpty(loginVO.getPassword())) {
            throw new BusinessException(MemberCodeMsg.PARAM_NOT_EMPTY);
        }
        //根据手机号码去查是否有这个用户
        User user = this.findById(Long.parseLong(loginVO.getUsername()));
        if (user == null) {
            throw new BusinessException(MemberCodeMsg.LOGIN_ERROR);
        }
        //校验密码
        String encyMd5Pwd = Md5Util.encyMd5(loginVO.getPassword(), user.getSalt());
        if (!encyMd5Pwd.equals(user.getPassword())) {
            throw new BusinessException(MemberCodeMsg.LOGIN_ERROR);
        }
        String token = createToken(user);
        return token;
    }

    @Override
    public Boolean refreshToken(String token) {
        Boolean exits = redisService.exits(MemberRedsKeyPrefix.USER_TOKEN_KEYPREFIX, token);
        if (exits) {
            redisService.expire(MemberRedsKeyPrefix.USER_TOKEN_KEYPREFIX, token);
            return true;
        }
        return false;
    }

    @Override
    public User getCurrent(String token) {
        User user = redisService.get(MemberRedsKeyPrefix.USER_TOKEN_KEYPREFIX, token, User.class);
        return user;
    }

    private String createToken(User user) {
        String token = UUID.randomUUID().toString().replace("-", "");
        //把user对象放到redis中
        redisService.set(MemberRedsKeyPrefix.USER_TOKEN_KEYPREFIX, token, user);
        return token;
    }
}